package com.pearadmin.pro.modules.stu.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pearadmin.pro.common.web.base.page.PageResponse;
import com.pearadmin.pro.common.web.base.page.Pageable;
import com.pearadmin.pro.modules.stu.domain.StuBusp;
import com.pearadmin.pro.modules.stu.domain.StuPurpose;
import com.pearadmin.pro.modules.stu.domain.StuRemind;
import com.pearadmin.pro.modules.stu.domain.StuTranscriptAdd;
import com.pearadmin.pro.modules.stu.param.StuBuspRequest;
import com.pearadmin.pro.modules.stu.repository.StuBuspRepository;
import com.pearadmin.pro.modules.stu.repository.StuPurposeRepository;
import com.pearadmin.pro.modules.stu.repository.StuRemindRepository;
import com.pearadmin.pro.modules.stu.repository.StuTranscriptAddRepository;
import com.pearadmin.pro.modules.stu.service.StuBuspService;
import com.pearadmin.pro.modules.stu.service.StuPurposeService;
import com.pearadmin.pro.modules.stu.service.StuTranscriptAddService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;


/**
 * 商机管理-学生信息Service业务层处理
 *
 * @author chenJian
 * @date 2021-09-09
 */
@Service
public class StuBuspServiceImpl extends ServiceImpl<StuBuspRepository, StuBusp> implements StuBuspService {
    @Resource
    private StuBuspRepository stuBuspRepository;
    @Autowired
    private StuBuspService stuBuspService;
    @Autowired
    private StuTranscriptAddService stuTranscriptAddService;
    @Autowired
    private StuTranscriptAddRepository stuTranscriptAddRepository;
    @Autowired
    private StuPurposeRepository stuPurposeRepository;
    @Autowired
    private StuPurposeService stuPurposeService;
    @Autowired
    private StuRemindRepository stuRemindRepository;

    @Override
    public boolean stuSaveOrUpdate(StuBusp stuBusp) {
        stuBuspService.saveOrUpdate(stuBusp);
        if (StringUtils.isNotBlank(stuBusp.getTranscriptAdd())) {//学生商机成绩单地址信息
            JSONArray jsonArray = (JSONArray) JSONArray.parse(stuBusp.getTranscriptAdd());
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                Object id = jsonObject.get("id");
                if (id.equals("0")) {
                    StuTranscriptAdd transcriptAdd = new StuTranscriptAdd();
                    transcriptAdd.setBuspId(stuBusp.getId());
                    transcriptAdd.setPostalCode(Convert.toStr(jsonObject.get("postalCode")));
                    transcriptAdd.setRecName(Convert.toStr(jsonObject.get("recName")));
                    transcriptAdd.setRecPhone(Convert.toStr(jsonObject.get("recPhone")));
                    transcriptAdd.setRecAdd(Convert.toStr(jsonObject.get("recAdd")));
                    transcriptAdd.setTranType(Convert.toLong(jsonObject.get("tranType")));
                    transcriptAdd.setEmail(Convert.toStr(jsonObject.get("email")));
                    transcriptAdd.setBackEmail(Convert.toStr(jsonObject.get("backEmail")));
                    transcriptAdd.setCreateTime(LocalDateTime.now());
                    transcriptAdd.setUpdateTime(LocalDateTime.now());
                    stuTranscriptAddService.saveOrUpdate(transcriptAdd);
                } else {
                    StuTranscriptAdd transcriptAdd1 = stuTranscriptAddRepository.selectById((Serializable) id);
                    transcriptAdd1.setPostalCode(Convert.toStr(jsonObject.get("postalCode")));
                    transcriptAdd1.setRecName(Convert.toStr(jsonObject.get("recName")));
                    transcriptAdd1.setRecPhone(Convert.toStr(jsonObject.get("recPhone")));
                    transcriptAdd1.setRecAdd(Convert.toStr(jsonObject.get("recAdd")));
                    transcriptAdd1.setTranType(Convert.toLong(jsonObject.get("tranType")));
                    transcriptAdd1.setEmail(Convert.toStr(jsonObject.get("email")));
                    transcriptAdd1.setBackEmail(Convert.toStr(jsonObject.get("backEmail")));
                    transcriptAdd1.setUpdateTime(LocalDateTime.now());
                    stuTranscriptAddRepository.updateById(transcriptAdd1);
                }
            }
        }
        if (StringUtils.isNotBlank(stuBusp.getPurpose())) {//学生商机意向信息
            JSONArray jsonArray = (JSONArray) JSONArray.parse(stuBusp.getPurpose());
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                Object id = jsonObject.get("id");
                if (id.equals("0")) {
                    StuPurpose purpose = new StuPurpose();
                    purpose.setBuspId(stuBusp.getId());
                    purpose.setSchool(jsonObject.get("school").toString());
                    purpose.setProject(jsonObject.get("project").toString());
                    purpose.setCourse(jsonObject.get("course").toString());
                    purpose.setAuthStatus(jsonObject.get("authStatus").toString());
                    purpose.setAuthUrl(jsonObject.get("authUrl").toString());
                    purpose.setFailCause(jsonObject.get("failCause").toString());
                    purpose.setCreateTime(LocalDateTime.now());
                    purpose.setUpdateTime(LocalDateTime.now());
                    stuPurposeService.saveOrUpdate(purpose);
                } else {
                    StuPurpose purpose1 = stuPurposeRepository.selectById((Serializable) id);
                    purpose1.setSchool(jsonObject.get("school").toString());
                    purpose1.setProject(jsonObject.get("project").toString());
                    purpose1.setCourse(jsonObject.get("course").toString());
                    purpose1.setAuthStatus(jsonObject.get("authStatus").toString());
                    purpose1.setAuthUrl(jsonObject.get("authUrl").toString());
                    purpose1.setFailCause(jsonObject.get("failCause").toString());
                    purpose1.setUpdateTime(LocalDateTime.now());
                    stuPurposeRepository.updateById(purpose1);
                }
            }
        }
        return true;
    }
    /**
     * 查询商机管理-学生信息
     *
     * @param id 商机管理-学生信息ID
     * @return 商机管理-学生信息
     */
    @Override
    public StuBusp selectStuBuspById(Long id) {
        StuBusp busp = stuBuspRepository.selectById(id);
        //地址单明细
        LambdaQueryWrapper<StuTranscriptAdd>  transcriptAddLambdaQueryWrapper=new LambdaQueryWrapper<>();
        transcriptAddLambdaQueryWrapper.eq(StuTranscriptAdd::getBuspId,busp.getId());
        List<StuTranscriptAdd> stuTranscriptAdds = stuTranscriptAddRepository.selectList(transcriptAddLambdaQueryWrapper);
        //意向课程明细
        LambdaQueryWrapper<StuPurpose>  purposeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        purposeLambdaQueryWrapper.eq(StuPurpose::getBuspId,busp.getId());
        List<StuPurpose> stuPurposes = stuPurposeRepository.selectList(purposeLambdaQueryWrapper);
        //提醒消息明细
        LambdaQueryWrapper<StuRemind>  remindLambdaQueryWrapper=new LambdaQueryWrapper<>();
        remindLambdaQueryWrapper.eq(StuRemind::getBuspId,busp.getId());
        List<StuRemind> stuReminds = stuRemindRepository.selectList(remindLambdaQueryWrapper);
        busp.setStuTranscriptAdds(stuTranscriptAdds);
        busp.setStuPurposes(stuPurposes);
        busp.setStuReminds(stuReminds);
        return busp;
    }

    /**
     * 查询商机管理-学生信息
     *
     * @param request
     * @return 商机管理-学生信息 分页集合
     */
    @Override
    public PageResponse<StuBusp> page(StuBuspRequest request) {
        LambdaQueryWrapper<StuBusp> query = new LambdaQueryWrapper<StuBusp>();
        query.like(ObjectUtil.isNotEmpty(request.getStuName()), StuBusp::getStuName, request.getStuName());
        query.eq(ObjectUtil.isNotEmpty(request.getChnSource()), StuBusp::getChnSource, request.getChnSource());
        query.like(ObjectUtil.isNotEmpty(request.getColName()), StuBusp::getColName, request.getColName());
        query.gt(ObjectUtil.isNotEmpty(request.getCreateBtime()),StuBusp::getCreateTime,request.getCreateBtime());
        query.lt(ObjectUtil.isNotEmpty(request.getCreateEtime()),StuBusp::getCreateTime,request.getCreateEtime());
        query.like(ObjectUtil.isNotEmpty(request.getInterDegree()), StuBusp::getInterDegree, request.getInterDegree());
        query.like(ObjectUtil.isNotEmpty(request.getSaleHead()), StuBusp::getActHead, request.getSaleHead());
        query.like(ObjectUtil.isNotEmpty(request.getAsdHead()), StuBusp::getAsdHead, request.getAsdHead());
        query.like(ObjectUtil.isNotEmpty(request.getActHead()), StuBusp::getActHead, request.getActHead());
        if(null!=request.getColBtime()){
            Date colBtime = request.getColBtime();//入学时间
            LocalDate localDate = colBtime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear());
            LocalDate lastDayOfYear = localDate.with(TemporalAdjusters.lastDayOfYear());
            query.gt(ObjectUtil.isNotEmpty(request.getColBtime()), StuBusp::getColBtime, firstDayOfYear.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
            query.lt(ObjectUtil.isNotEmpty(request.getColBtime()), StuBusp::getColBtime, lastDayOfYear.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        }

        return Pageable.of(request, (() -> stuBuspRepository.selectList(query)));
    }


    @Override
    public StuBusp selectStuBuspByWeixinunid(String unionid) {
        LambdaQueryWrapper<StuBusp> query = new LambdaQueryWrapper<StuBusp>();
        query.eq(ObjectUtil.isNotEmpty(unionid), StuBusp::getUnionid, unionid);
        return stuBuspRepository.selectOne(query);
    }

    @Override
    public StuBusp selectStuBuspByPhone(String phone) {
        LambdaQueryWrapper<StuBusp> query = new LambdaQueryWrapper<StuBusp>();
        query.eq(ObjectUtil.isNotEmpty(phone), StuBusp::getLocalPhone, phone);
        return stuBuspRepository.selectOne(query);
    }

}
